import "dart:io";

import 'package:dio/dio.dart';
import "package:dio/io.dart";
import 'package:flutter_plugin/global/global_controller.dart';
import "../constant/sp_key.dart";
import "../util/sputil.dart";
import "../util/toast_util.dart";
import 'base/BaseEntity.dart';
import "base/BaseListEntity.dart";
import 'base/baseApi.dart';
import 'base/NWMethod.dart';
import 'base/ErrorEntity.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

class DioManager {
  static final DioManager _shared = DioManager._internal();

  factory DioManager() => _shared;
  var dio = Dio();

  DioManager._internal() {
    if (dio == null) {
      throw Exception('DioManager is not initialized!');
    }
    BaseOptions options = BaseOptions(
      baseUrl: NWApi.baseApi,
      contentType: Headers.jsonContentType,
      responseType: ResponseType.json,
      receiveDataWhenStatusError: false,
      //连接超时
      connectTimeout: const Duration(milliseconds: 10000),
      //接收超时
      receiveTimeout: const Duration(milliseconds: 10000),
    );
    // 头部添加lan
    dio = Dio(options);
    dio!.interceptors.add(LogInterceptor(responseBody: false)); // 添加日志拦截器
    (dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate = (client) {
      client.badCertificateCallback = (cert, host, port) {
        return true; // 返回true强制通过
      };
    };
  }

  // 请求，返回参数为 T
  // method：请求方法，NWMethod.POST等
  // path：请求地址
  // params：请求参数
  // success：请求成功回调
  // error：请求失败回调
  Future requestAccept<T>(String path,
      {withLoading = false,
      loadText = "加载中...",
      NWMethod method = NWMethod.POST,
      Map? params,
      Map<String, String>? header,
      Function(T)? success,
      Function(ErrorEntity)? error}) async {
    if (withLoading) {
      EasyLoading.show(status: loadText);
    }
    final _headers = header ?? headers();
    Options options = Options()
      ..method = NWMethodValues[method]
      ..headers = _headers;
    try {
      Response response = await dio!.request(path, data: params, options: options);
      if (withLoading) {
        EasyLoading.dismiss();
      }
      if (response != null) {
        print('DioManager response ${response.data}');
        BaseEntity entity = BaseEntity<T>.fromJson(response.data);
        if (entity.responseCode.toString() == "10000") {
          success!(entity.entry);
          return entity.entry;
        } else {
          error!(ErrorEntity(code: entity.responseCode, message: entity.message));
          return entity.entry;
        }
      } else {
        print('DioManager response is null');
        error!(ErrorEntity(code: "-1", message: "未知错误"));
        ToastUtil.showTip('未知错误');
      }
      // ignore: deprecated_member_use
    } on DioError catch (e) {
      if (withLoading) {
        EasyLoading.dismiss();
      }
      print('DioManager DioError ${e.type}');
      error!(createErrorEntity(e));
    }
  }

  // 请求，返回参数为 List
  // method：请求方法，NWMethod.POST等
  // path：请求地址
  // params：请求参数
  // success：请求成功回调
  // error：请求失败回调
  Future requestListAccept<T>(String path,
      {withLoading = false,
      loadText = "加载中...",
      NWMethod method = NWMethod.POST,
      Map? params,
      required Function(List<T>) success,
      Function(ErrorEntity)? error}) async {
    if (withLoading) {
      EasyLoading.show(status: loadText);
    }
    final _headers = headers();
    Options options = Options()
      ..method = NWMethodValues[method]
      ..headers = _headers;
    try {
      var response = await dio!.request(path, data: params, options: options);
      if (response != null) {
        print('DioManager response ${response.data}');
        BaseListEntity<T> entity = BaseListEntity<T>.fromJson(response.data);
        if (entity!.responseCode.toString() == '10000') {
          success(entity.entry);
        } else {
          error!(ErrorEntity(code: entity.responseCode, message: entity.message));
        }
      } else {
        error!(ErrorEntity(code: "-1", message: "未知错误"));
      }
    } on DioError catch (e) {
      error!(createErrorEntity(e));
    }
  }

  // 错误信息
  ErrorEntity createErrorEntity(DioError error) {
    switch (error.type) {
      case DioErrorType.cancel:
        {
          return ErrorEntity(code: " -1", message: "请求取消");
        }
        break;
      // ignore: deprecated_member_use
      case DioErrorType.connectionTimeout:
        {
          return ErrorEntity(code: "-1", message: "连接超时");
        }
        break;
      case DioErrorType.sendTimeout:
        {
          return ErrorEntity(code: "-1", message: "请求超时");
        }
        break;
      case DioErrorType.receiveTimeout:
        {
          return ErrorEntity(code: "-1", message: "响应超时");
        }
        break;
      case DioErrorType.badResponse:
        {
          try {
            int? errCode = error.response!.statusCode;
            String? errMsg = error.response!.statusMessage;
            print('DioManager DioError errCode:$errCode errMsg:$errMsg');
            switch (errCode) {
              case 402:
                {
                  GlobalController.to.logout();
                  return ErrorEntity(code: "$errCode", message: "多端登录");
                }
              default:
                {
                  return ErrorEntity(code: "$errCode", message: "未知错误");
                }
            }
            return ErrorEntity(code: "$errCode", message: errMsg);
//          switch (errCode) {
//            case 400: {
//              return ErrorEntity(code: errCode, message: "请求语法错误");
//            }
//            break;
//            case 403: {
//              return ErrorEntity(code: errCode, message: "服务器拒绝执行");
//            }
//            break;
//            case 404: {
//              return ErrorEntity(code: errCode, message: "无法连接服务器");
//            }
//            break;
//            case 405: {
//              return ErrorEntity(code: errCode, message: "请求方法被禁止");
//            }
//            break;
//            case 500: {
//              return ErrorEntity(code: errCode, message: "服务器内部错误");
//            }
//            break;
//            case 502: {
//              return ErrorEntity(code: errCode, message: "无效的请求");
//            }
//            break;
//            case 503: {
//              return ErrorEntity(code: errCode, message: "服务器挂了");
//            }
//            break;
//            case 505: {
//              return ErrorEntity(code: errCode, message: "不支持HTTP协议请求");
//            }
//            break;
//            default: {
//              return ErrorEntity(code: errCode, message: "未知错误");
//            }
//          }
          } on Exception catch (_) {
            return ErrorEntity(code: "-1", message: "未知错误");
          }
        }
        break;
      default:
        {
          return ErrorEntity(code: " -1", message: error.message);
        }
    }
  }

  static Map<String, String> headers() {
    Map<String, String> headers = <String, String>{};
    headers["Content-Type"] = "application/json;charset=utf-8"; //编码
    headers["os"] = Platform.isIOS ? "IOS" : "Android"; //手机操作系统
    headers["User-type"] = "1"; //用户类型 1.tv 2.app端
    headers["packageName"] = "com.xdr.family";
    headers["v"] = "V2.1.0.20240104";
    headers["tenantId"] = "familyGuard";
    headers["Mobile-Channel"] = "0";
    headers["Mobile-Version"] = "Android 13";
    headers["Mobile-Model"] = "TYH123U";
    String sn = SPUtil.instance.get(SPKey.sn) ?? "";
    headers["sn"] = sn; //请求sn
    String token = SPUtil.instance.get(SPKey.TOKEN) ?? "";
    if (token.isNotEmpty) {
      headers["Authorization"] = token; //用户token
    }
    return headers;
  }
}
